#include "main.h"

OpenglWindow	*window=NULL;
FILE			*file;


void filelog(char *info)
{
	SYSTEMTIME st;
	
	GetSystemTime(&st);
		
	file = fopen("log.txt", "a");	// append
	if (file != NULL)
	{
		fprintf(file, "(%d) - %s\n", st.wMilliseconds, info); 
		fclose(file);
	}
}

void draw()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();

	glTranslatef(-1.5f, 0.0f,-6.0f);

	glBegin(GL_TRIANGLES);
		glVertex3f( 0.0f, 1.0f, 0.0f);
		glVertex3f(-1.0f,-1.0f, 0.0f);
		glVertex3f( 1.0f,-1.0f, 0.0f);
	glEnd();
}

LRESULT WndProc(HWND hWnd, UINT uMsg,WPARAM wParam, LPARAM lParam)
{
	switch (uMsg)
	{
	case WM_CLOSE:
		{
			PostQuitMessage(0);
			return 0;
		}
	case WM_SIZE:
		{
			window->resize(LOWORD(lParam), HIWORD(lParam));
			return 0;
		}
	}
	
	return DefWindowProc(hWnd, uMsg, wParam, lParam);

}


int __stdcall WinMain(          HINSTANCE hInstance,
    HINSTANCE hPrevInstance,
    LPSTR lpCmdLine,
    int nCmdShow)
{
	MSG				msg;
	bool			quit=false;

	filelog("Starting TV Gids\n");

	try {
		window = new OpenglWindow("TV Gids", &WndProc);

		window->show();

		while ( !quit )
		{
			if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
			{
				if (msg.message == WM_QUIT)
					quit = true;
				else
				{
					TranslateMessage(&msg);
					DispatchMessage(&msg);
				}
			} else {
				draw();
				filelog("tick");
				window->swapBuffers();
				// todo
			}
		}
	
	} 
	catch ( OpenglWindowException &ex )	{
		MessageBox(NULL,ex.message,"OpenglWindow error", MB_OK|MB_ICONERROR);
		delete[] window;
	}
	catch ( ... ) {
		MessageBox(NULL, "Error.","OpenglWindow error", MB_OK|MB_ICONERROR);
		delete[] window;
	}

	window->destroy();
	filelog("End of TV-Gids");

	
	return (int)msg.wParam;
}